<?php
namespace Helpers;

class CaptchaImage {

    private $disturbCode = '1235467890qwertyuipkjhgfdaszxcvbnm';
    private $fontUrl     = 'files/AdobeGothicStd-Bold.otf';
    private $image;
    private $code;
    private $width;
    private $height;

    function __construct($code, $width = 100, $height = 30) {
        $this->code     = $code;
        $this->width    = $width;
        $this->height   = $height;
    }

    public function imageOut(){
        $this->image = $this->createImage();
        $this->setBackColor();
        $this->setCode();
        $this->setDisturbCode();
        header('Pragma: no-cache');
        header('Content-Type: image/gif');
        ImageGIF($this->image);
        ImageDestroy($this->image);
    }

    private function createImage(){
        return imagecreate($this->width, $this->height);
    }

    private function setBackColor(){
        imagefill($this->image,0,0, ImageColorAllocate($this->image, rand(200,255), rand(200,255), rand(200,255)));
    }

    private function setCode(){
        $y        = floor($this->height / 2) + floor($this->height / 4);
        $fontSize = rand($this->height / 2, $this->height - 5);
        $counts   = strlen($this->code);
        for ($i = 0; $i < $counts; $i++) {
            $x     = floor($this->width / $counts) * $i + 8;
            $color = ImageColorAllocate($this->image, rand(0,50), rand(50,100), rand(100,140));
            imagettftext($this->image, $fontSize, rand(-20,30), $x, $y, $color, $this->fontUrl, $this->code[$i]);
        }
    }

    private function setDisturbCode(){
        $num = floor($this->height);
        $disturbCount = strlen($this->disturbCode);
        $minSize = floor($this->height / 8);
        $maxSize = floor($this->height / 4);
        for ($i = 0; $i < $num; $i++){
            $x = rand(0, $this->width);
            $y = rand(0, $this->height);
            $char  = $this->disturbCode[rand(0, $disturbCount - 1)];
            $color = ImageColorAllocate($this->image, rand(40, 140), rand(40, 140), rand(40, 140));
            imagettftext($this->image, rand($minSize, $maxSize), rand(0, 360), $x, $y, $color, $this->fontUrl, $char);
        }
    }

}